package com.pn.taikao.service.impl;

import com.pn.taikao.common.ResultCode;
import com.pn.taikao.entity.User;
import com.pn.taikao.exception.BusinessException;
import com.pn.taikao.mapper.UserMapper;
import com.pn.taikao.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public Long createUser(User user) {
        if (StringUtils.hasText(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        if (user.getCreateTime() == null) {
            user.setCreateTime(LocalDateTime.now());
        }
        if (user.getUpdateTime() == null) {
            user.setUpdateTime(LocalDateTime.now());
        }
        if (user.getDelFlag() == null) {
            user.setDelFlag("0");
        }
        userMapper.insert(user);
        return user.getId();
    }

    @Override
    public void updateUser(User user) {
        if (StringUtils.hasText(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public User getByEmail(String email) {
        return userMapper.selectByEmail(email);
    }

    @Override
    public List<User> list(String username, String roleType, int page, int size) {
        int offset = Math.max(page, 1);
        offset = (offset - 1) * Math.max(size, 1);
        return userMapper.selectPage(username, roleType, offset, size);
    }

    @Override
    public long count(String username, String roleType) {
        return userMapper.count(username, roleType);
    }

    @Override
    public Long register(User user) {
        // 基本去重校验（数据库也有唯一约束）
        if (StringUtils.hasText(user.getUsername())) {
            User exist = userMapper.selectByUsername(user.getUsername());
            if (exist != null) {
                throw new BusinessException(ResultCode.USERNAME_EXISTS);
            }
        }
        if (StringUtils.hasText(user.getEmail())) {
            User exist = userMapper.selectByEmail(user.getEmail());
            if (exist != null) {
                throw new BusinessException(ResultCode.EMAIL_EXISTS);
            }
        }
        return createUser(user);
    }

    @Override
    public User authenticate(String usernameOrEmail, String rawPassword) {
        User found = null;
        if (usernameOrEmail == null) {
            return null;
        }
        // 先按用户名，再按邮箱
        found = userMapper.selectByUsername(usernameOrEmail);
        if (found == null) {
            found = userMapper.selectByEmail(usernameOrEmail);
        }
        if (found == null) {
            return null;
        }
        if (!StringUtils.hasText(found.getPassword())) {
            return null;
        }
        boolean ok = passwordEncoder.matches(rawPassword, found.getPassword());
        return ok ? found : null;
    }
}


